package com.first.system.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.first.common.pojo.AclUser;
import com.first.common.vo.Result;
import com.first.system.service.LoginService;
import com.first.system.vo.LoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @program: finrsteducation-parent
 * @description: 管理界面登录
 * @author: 张玉森
 * @create: 2023-05-25 20:48
 **/
@RestController
@RequestMapping("system/admin")
@Api(tags = "登录界面")
public class LoginController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private LoginService loginService;



    @GetMapping("logout")
    @ApiOperation("角色退出接口")
    public Result logut(HttpServletRequest request) {
        //获取请求头
        String token = request.getHeader("token");
        redisTemplate.delete("user::" + token);
        if (redisTemplate.hasKey("user::" + token)) {
            return Result.fail("退出失败");
        }
        return Result.success(null);

    }
    @PostMapping("/login")
    @ApiOperation(value = "登录接口")
    public Result login(@RequestBody LoginVo loginVo) {
        AclUser user = loginService.findByNameAndPwd(loginVo.getUsername(), loginVo.getPassword());
        if (user != null) {
            if (user.getStatus().equals(0)) {
                //表示成功
                String token = IdUtil.simpleUUID();
                user.setPassword(null);
                redisTemplate.opsForValue().set("user::" + token, JSON.toJSONString(user), 30, TimeUnit.MINUTES);
                return Result.success(token);
            } else {
                //表示该账号已经被冻结
                return Result.fail("该账号被冻结了，请联系管理员");
            }
        }
        return Result.fail("账号或密码错误");
    }


}
